<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\ExchangeCouponOrder as ExchangeCouponOrderModel;
use app\model\app\ExchangeCoupon as ExchangeCouponModel;
use app\model\app\GameOrder as GameOrderModel;
use app\model\pay\Pay as PayModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use think\helper\Str;
use wechat\mch\Pay as WechatMchPay;
use yicmf\tools\FlowSn;
use yicmf\tools\HttpService;
use yicmf\tools\Rsa;

class ExchangeCoupon extends Base
{

    protected $key = 'ee2e43135b5bfed5128d358df619efad';
    protected $userName = 'qifan123';


    public function endPay($param)
    {
        try {
            $order = ExchangeCouponOrderModel::where('sn', $param['external_orderno'])->where('status',1)->find();
            if (!$order) {
                throw new Exception('兑换不存在');
            }
            Db::startTrans();
            $order->allowField(['status','order_sn', 'msg', 'mobile', 'name', 'actual_price', 'pay_price', 'img', 'kami'])
                ->save($param);
            $task = UserTaskModel::where('task_type', 21)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $task['step'] = $order['status'];
            if ($order['status'] == 4 ) {
                $task['status'] = 2;
            } elseif ($order['status'] == 3 || $order['status'] == 2 || $order['status'] == 6 || $order['status'] == 1) {
                $task['status'] = 1;
            } else {
                $task['reason'] = $order['msg'];
                $task['status'] = 3;
            }
            /**
             * status==1    等待支付，下一时刻会变成2
             * status==2    等待发货，等待处理
             * status==3    已发货，物流派送中
             * status==4    交易成功，订单完成，虚拟充值商品订单成功为该状态
             * status==5    交易取消，订单失败，虚拟充值商品订单失败为该状态
             * status==6    处理中，正在处理
             */
            $task->save();
            if ($task['status'] == 2) {
                $user = UserModel::where('id', $task['user_id'])->find();
                if ($user) {
                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 38, $user['id'], $task['task_no'], 0, $order['branch_id'], 13);
                }
            }elseif ($task['status'] == 3) {
                // 退费
                $pay = PayModel::where('relation_id', $order['id'])->where('type', 'exchange')->find();
                if ($pay) {
                    if ($pay['payment_code'] == 'alipay') {
                        if ($pay['operation_type'] == 'FREEZE') {
                            // 预授权
                            Log::write(11221);
                            alipay_app_unfreeze_pay($pay, $pay['api_amount'], '订单取消自动退费');
                            $pay['status'] = -1;
                            $pay->save();
                        } else {
                            alipay_app_refund($pay['pay_sn'], $pay['api_amount'], '订单取消自动退费', '系统' . $pay['out_request_no']);
                            Log::write(1122);
                        }
                        $order['status'] = 8;
                    } elseif ($pay['payment_code'] == 'wxpay') {
                        // 微信退款
                        $re = wechat_app_pay_refund($pay, $pay['api_amount'], '订单取消自动退费');
                        if (isset($re['result_code']) && $re['result_code'] == 'SUCCESS') {
                            // 成功
                            $order['status'] = 8;
                            $pay['gmt_close'] = time_format();
                            $pay['refund_money'] = $pay['api_amount'];
                            $pay['receipt_amount'] = $pay['api_amount'];
                            $pay['status'] = -1;
                            $pay->save();
                        }
                    }
                }
            }
            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 支付了会员券，先第三方渠道
     * @param array $param
     * @param UserModel $user
     * @return array
     */
    public function pay($pay)
    {
        try {
            $order = ExchangeCouponOrderModel::where('id', $pay['relation_id'])->lock(true)->find();
            if (!$order) {
                throw new Exception('订单不存在');
            }

            // 更改订单
            $order['status'] = 1;
            $order['pay_time'] = time_format();
            if (!$order->save()) {
                throw new Exception('订单状态异常：订单状态改变错误');
            }

            $param = [];
            $param['timestamp'] = time();
            $param['userName'] = $this->userName;
            // 爱奇艺周卡
            $data['commodityId'] = $order['branch_id'];//商品编号
            $data['external_orderno'] = $order['sn'];//订单号
            $data['buyCount'] = 1;
            $re = md5($data['external_orderno'] . $this->key);
            $data['remark'] = $order['user_id'];
            $data['callbackUrl'] = (string)url('/api/notify/yqd/call', ['rsa' => $re], false, true);
            $data['externalSellPrice'] = $order['pay_price'];//商户平台卖价，小数类型，默认请传0，建议传入，防止商品价格变更造成溢价亏损
            $template = [];
            foreach ($order['template'] as $item) {
                $template[] = urlencode($item);
            }
            $data['template'] = $template;
            $param['data'] = json_encode($data);
            $param['sign'] = md5($param['timestamp'] . $param['data'] . $this->key);

            $re = HttpService::request('http://open.yiqida.cn/api/UserOrder/CreateOrder?timestamp=' . $param['timestamp'] . '&userName='
                . $param['userName'] . '&sign=' . $param['sign'], json_encode($data), 'POST');
            if ($re['content']['code'] != 200) {
                $order['msg'] = $re['content']['msg'];
                $order['status'] = 0;
                $order->save();

                if ($re['content']['code'] == 1003) {
                    // 下架
                    $exchange = ExchangeCouponModel::where('branch_id', $order['branch_id'])->update(['status' => 2]);
                }
            } else {
                $res = $re['content']['data'];
                $update = [];
                $update['sn'] = $data['external_orderno'];
                foreach ($res as $index => $item) {
                    $update[Str::snake($index)] = trim($item) ? trim($item) : null;
                }
                Log::write($res);
                $order->allowField(['order_id','order_sn', 'name', 'actual_price'])
                    ->save($update);
            }
            $task = UserTaskModel::where('task_type', 21)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['step'] = $order['status'];
                if ($order['status'] == 0) {
                    $task['status'] = 3;
                } else {
                    $task['status'] = 1;
                }
                $task->save();
            }

            $data['code'] = 0;
            $data['data'] = 1;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    public function info()
    {
        $exchange = ExchangeCouponModel::where('status', 1)->where('is_sale', 1)->order('info_time ASC')->find();
        if ($exchange) {
            try {
                $param = [];
                $param['timestamp'] = time();
                $param['userName'] = $this->userName;
                $data['id'] = $exchange['branch_id'];//商品编号
                $param['data'] = json_encode($data);
                $param['sign'] = md5($param['timestamp'] . $param['data'] . $this->key);
                $re = HttpService::request('http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo?timestamp=' . $param['timestamp'] . '&userName='
                    . $param['userName'] . '&sign=' . $param['sign'], json_encode($data), 'POST');

                if (is_array($re['content']) && $re['content']['code'] == 200) {
                    $res = $re['content']['data'];
                    $insert = [];
                    $insert['info_time'] = time_format();
                    foreach ($res as $index => $item) {
                        if ($item)
                        {
                            $insert[Str::snake($index)] = trim($item) ? trim($item) : null;
                            if ($index == 'template' && $item) {
                                $insert[Str::snake($index)] = json_decode($item, true);
                            }
                        }else{
                            $insert[Str::snake($index)] = null;

                        }

                    }
                    $re = $exchange->allowField(['status', 'is_pre_sale'
                        , 'pre_sale_s_time', 'pre_sale_e_time', 'name',
                        'actual_price', 'guide_price', 'price',
                        'delivery',
                        'branch_img',
                        'main_img',
                        'info_time',
                        'stock_amount'])->save($insert);

                }else{
                    $exchange['is_sale'] = 0;
                    $exchange->save();
                }

                $data['code'] = 0;
                $data['data'] = 1;
                $data['message'] = '操作成功';
            } catch (\Exception $e) {

                $data['code'] = 1;
                $data['f'] = $e->getFile();
                $data['l'] = $e->getLine();
                $data['message'] = $e->getMessage();
            }

        }

        return true;
    }

    public function balance()
    {
        $param = [];
        $param['timestamp'] = time();
        $param['userName'] = $this->userName;
        $param['sign'] = md5($param['timestamp'] . $this->key);
        $re = HttpService::request('http://open.yiqida.cn/api/UserInfo/GetMemberInfo?timestamp=' . $param['timestamp'] . '&userName='
            . $param['userName'] . '&sign=' . $param['sign']);

        if ($re['content']['code'] == 200) {
            if ($re['content']['data']['balance'] < 200) {
                dump($re['content']['data']['balance']);
            }
        }

        return true;
    }

    public function fail()
    {
        $orders = ExchangeCouponOrderModel::where('status', 0)->whereNull('order_no')->whereTime('create_time', '<', '-10 minutes')->select();
        foreach ($orders as $order) {
            $order['status'] = -1;
            $order->save();
            $task = UserTaskModel::where('task_type', 21)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['reason'] = '超时未支付';
                $task['status'] = 3;
                $task->save();
            }
        }
    }

    /**
     * 下单优惠券
     * @param array $param
     * @param UserModel $user
     * @return array
     */
    public function order($param, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请先登录');
            }

//            $exchange = ExchangeCouponModel::where('id', $param['branch_id'])->find();
            $exchange = ExchangeCouponModel::where('branch_id', $param['branch_id'])->find();
//            $exchange = ExchangeCouponModel::where('branch_id', 10000221)->find();
//            $exchange = ExchangeCouponModel::where('id', 495)->find();
            if (!$exchange) {
                throw new Exception('信息异常');
            }
            if ($exchange['status'] != 1) {
                throw new Exception('库存不足');
            }
            if ($exchange['is_sale'] != 1) {
                throw new Exception('接口已经下架');
            }
            if ($exchange['back_price'] <= 0) {
                throw new Exception('库存不足');
            }
            $order['user_id'] = $user['id'];
//            $order['branch_id'] = $exchange['id'];//'10000221';//10000608
            $order['branch_id'] = $param['branch_id'];//10000608
            $order['sn'] = FlowSn::build('9');
            $order['status'] = 0;
            $order['template'] = $param['template'];
            $order['amount'] = $exchange['sale_price'];
            $order['name'] = $exchange['name'];
            $order = ExchangeCouponOrderModel::create($order);
            if (!$order) {
                throw new Exception('订单创建失败');
            }
            $userTask['task_id'] = 13;
            $userTask['relation_id'] = $order['id'];
            $userTask['task_type'] = 21;
            $userTask['user_id'] = $user['id'];
            $userTask['agent_id'] = $user['agent_id'];
            $userTask['title'] = $exchange['name'];
            $userTask['logo'] = $exchange['branch_img'];
            $userTask['money'] = $order['amount'];
            $userTask['commission'] = $exchange['back_price'];
            $userTask['task_no'] = $order['sn'];
//            $userTask['end_time'] = time() + 30 * 86400;
            $userTask['step'] = 0;
            $userTask['submit_info'] = $param;
            $userTask['status'] = 0;
            $task = UserTaskModel::create($userTask);
            if (!$task) {
                throw new Exception('系统故障');
            }

            $insert = [];
            $insert['type'] = 'exchange';
            $insert['user_id'] = $user['id'];
            $insert['agent_id'] = $user['agent_id'];
//            $insert['payment_code'] = $this->param['payment_code'];
            $insert['payment_code'] =isset($param['payment_code'])?$param['payment_code']:'alipay';
            $insert['api_pay_status'] = '';
            $insert['pay_sn'] = $order['sn'];
            $insert['relation_id'] = $order['id'];
            $insert['total_amount'] = $order['amount'];
            $insert['title'] = '购买会员';
            $pay = PayModel::create($insert);
            if (!$pay) {
                throw new Exception('订单信息创建异常');
            }
            if (isset($param['is_h5']) && 1 == $param['is_h5']) {
                $pay['payment_code'] = 'alipay';
                $pay->save();
                $data['data']['pay']= ['webview' => 0, 'payment' => $insert['payment_code'], 'order_info' => alipay_h5_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];
            } else {
                // APP支付
                if ($insert['payment_code']  == 'wxpay') {
                    $pay_param['out_trade_no'] = $pay['pay_sn'];
                    $pay_param['trade_type'] = 'APP';
                    $pay_param['notify_url'] = (string)url('/api/notify/pay/wechat', [], false, true);
                    $pay_param['total_fee'] = $pay['total_amount'] * 100;
                    $pay_param['attach'] = $pay['type'];
                    $pay_param['detail'] = '';// 保留
                    $pay_param['body'] = $pay['title'];
                    $pay_param['device_info'] = 'app';
                    $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
                    $pay_result = $WechatMchPay->unifiedorder($pay_param);
                    if ('fail' == strtolower($pay_result['return_code'])) {
                        throw new Exception($pay_result['return_msg']);
                    }
                    if ('fail' == strtolower($pay_result['result_code'])) {
                        throw new Exception($pay_result['err_code_des']);
                    }
                    $orderInfo = $WechatMchPay->appSign($pay_result['prepay_id'], $pay_result['nonce_str']);
                    $data['data']['pay'] = ['webview' => 0, 'payment' => 'wxpay', 'order_info' => $orderInfo];;
                } else {
                    //            $webview = (string)url('/api/notify/alipay/h5',['pay_sn'=>$pay['pay_sn']],true,true);
//            $this->param['pay'] = ['webview'=>1,'url'=>$webview,'payment' => $insert['payment_code'], 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];
                 //   $this->param['pay'] = ['webview' => 0, 'payment' => $insert['payment_code'], 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];
                    $data['data']['pay'] = ['payment' => 'alipay', 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];;

                }
            }
              $data['code'] = 0;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }
}
